package com.cai.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.cai.constant.MessageConstant;
import com.cai.constant.RedisConstant;
import com.cai.entity.PageResult;
import com.cai.entity.QueryPageBean;
import com.cai.entity.Result;
import com.cai.pojo.Setmeal;
import com.cai.service.SetmealService;
import com.cai.utils.aliyunUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.UUID;

/**
 * 体检套餐管理
 */

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired //注入redis连接池
    private JedisPool jedisPool;

    @Reference
    private SetmealService setmealService;
    //图片上传
    @RequestMapping("/upload")
    public Result uoLoad(@RequestParam("imgFile") MultipartFile imgFile){
        try {
            String originalFilename = imgFile.getOriginalFilename();//获取原文件名
            int index = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(index - 1);//截取后缀名.jpg
            String fileName= UUID.randomUUID().toString()+suffix;//上传文件名
            //调用工具类上传图片
            aliyunUtil.fileUpload(fileName,imgFile.getBytes());
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
    //添加套餐
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[]checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
    }
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = setmealService.pageQuery(queryPageBean);
        return pageResult;
    }

    /**
     * 查询所有套餐信息用于反显
     * @return
     */
    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<Setmeal> list = setmealService.findAllSetmeal();
            return new Result(true,"success",list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询所有套餐信息失败");
        }
    }
}
